import sys

sys.path.append("..")  # 也可以这样sys.path.append("../..")
# 换脸的测试

import os
from celery import group
from celerytask import app
import time

# 获得任务函数的引用
process_workflow = app.tasks['celerytask.tasks.start_V1']  #celerytask.tasks.start_V1
process_workflow_V3 = app.tasks['celerytask.tasks.start_V3']  #celerytask.tasks.start_V1
# verify_face = app.tasks['insightface_celery.face_base.verify_face']  # 人脸验证


# 用celery 来实现分布式的任务的任务发布
def process_images(user_image, target_directory, output_directory_name,GFPGANAmount=100):
    # 确保输出目录存在
    os.makedirs(output_directory_name, exist_ok=True)

    # 从目标目录中获取所有图片文件
    target_files = [os.path.join(target_directory, f) for f in os.listdir(target_directory) if
                    f.lower().endswith(('.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tif', '.tiff'))]

    signatures = []
    for target_file in target_files:
        output_file_path = os.path.join(output_directory_name, os.path.basename(target_file))
        signatures.append(process_workflow.s(user_image, target_file, output_file_path,GFPGANAmount))

    # 创建一个group，里面有你的所有任务签名
    job = group(signatures)

    # 记录开始时间
    start_time = time.time()

    # 执行这个group，并返回一个组结果
    result = job.apply_async()

    # 通过get()方法等待所有任务完成，并获取结果(超过30分钟以后就会自动抛出异常了)
    group_results = result.get(timeout=1800)

    # 记录结束时间
    end_time = time.time()

    # 计算并打印总时间
    total_time = end_time - start_time
    print(f"All tasks completed in {total_time} seconds.")

    return output_directory_name



def process_images_many_face(face_pairs_list, full_video_paths, output_directory_name,GFPGANAmount=100):
    # 确保输出目录存在
    os.makedirs(output_directory_name, exist_ok=True)
    signatures = []
    for target_file in full_video_paths:
        # TODO:" 没有错! 但是问题是!没有换脸?
        output_file_path = os.path.join(output_directory_name, os.path.basename(target_file))
        signatures.append(process_workflow_V3.s(target_file, face_pairs_list, output_file_path,GFPGANAmount))

    # 创建一个group，里面有你的所有任务签名
    job = group(signatures)

    # 记录开始时间
    start_time = time.time()

    # 执行这个group，并返回一个组结果
    result = job.apply_async()

    # 通过get()方法等待所有任务完成，并获取结果
    group_results = result.get(timeout=1800)

    # 记录结束时间
    end_time = time.time()

    # 计算并打印总时间
    total_time = end_time - start_time
    print(f"All tasks completed in {total_time} seconds.")
    # from loguru import logger
    # logger.debug(f"换脸的结果是{group_results}")

    return output_directory_name


if __name__ == '__main__':
    pass
    # 测试的可以用这个
# user_image = "insightface_celery/users_images/04273bccccf49b4e986d574485148038.png"
# target_directory = "insightface_celery/source_videos_frame/30d47343065b99a55fc26a235bde3074_15/"
# output_directory_name = f"insightface_celery/user_swapper_face_frames/30d47343065b99a55fc26a235bde3074_15_{int(time.time())}"
#
# output_path = process_images(user_image, target_directory, output_directory_name)
# print(f"Processed images saved in {output_path}.")
